package innersort.swap;

import innersort.speed.SortStrategy;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-03 13:54
 * @ Description :
 */
public class BubbleSort implements SortStrategy
{
    public static void main(String[] args)
    {
        //int[] array = {3, 9, -1, 10, 20};
        //int[] array = new int[80000];
        //for (int i = 0; i < 80000; i++)
        //{
        //    array[i] = (int)(Math.random() * 8000000);
        //}
        //Date date = new Date();
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String beforeSort = format.format(date);
        //System.out.println("beforeSort = " + beforeSort);
        //
        //bubbleSort(array);
        //
        //Date date1 = new Date();
        //String afterSort = format.format(date1);
        //System.out.println("afterSort = " + afterSort);
        


    }

    @Override
    public void sort(int[] array)
    {
        bubbleSort(array);
    }

    private static int[] bubbleSort(int[] array)
    {
        boolean flag = false;//表示在一趟排序中是否进行了交换

        //i: 表示需要进行多少次排序
        for (int i = 0; i < array.length - 1; i++)
        {

            //j: 表示一次排序中的两两比较过程
            // - i 表示每一次排序时去掉已经排好顺序的元素
            for (int j = 0; j < array.length - 1 - i; j++)
            {
                //这里数组不越界: j是小于不是等于,j只会到达数组的倒数第二个元素
                if (array[j] > array[j + 1])
                {
                    flag = true;
                    array[j] = array[j] - array[j + 1];
                    array[j + 1] = array[j] + array[j + 1];
                    array[j] = array[j + 1] - array[j];
                }
            }
            //System.out.println("第" + (i + 1) + "次排序后的序列为:" + Arrays.toString(array));
            if (!flag)
            {
                break;
            }
            else
            {
                flag = false;
            }
        }
        return array;
    }


    private static void swapTwo(Integer val1, Integer val2)
    {
        int temp = 0;
        temp = val1;
        val1 = val2;
        val2 = temp;
    }

    private static void swapTwo2(Integer val1, Integer val2)
    {
        val1 = val1 - val2;
        val2 = val1 + val2;
        val1 = val2 - val1;
    }

}
